<template>
  <div class="e-box" :style="{ height:`calc(100% - ${36 + height}px)`}">
    <div class="select">
      <el-select :disabled="language !== '不限'" v-model="answer.language" @change="changeLanguage">
        <el-option v-for="lan in lans" :key="lan" :value="lan">{{ lan }}</el-option>
      </el-select>
    </div>
    <div id="codeEditBox"></div>
    <div class="submit">
      <el-button type="primary" @click="submitCode" :loading="loading">运行</el-button>
    </div>
  </div>
  <div class="bottom-container">
    <div class="sub-box" >
      <span @click="switchPanel(true)" class="select-plane" :style="{  }" :class="{'on-panel':inputing}">输入 </span><!-- backgroundColor:inputing?'':'#f6f6f6' -->
     <span @click="switchPanel(false)" class="select-plane" :style="{  }" :class="{'on-panel':!inputing}">输出</span>
     <span @click="open" class="btn"><el-icon><ArrowUpBold v-if="!test" /><ArrowDownBold v-else /></el-icon></span>
     
    </div>
    <div class="msg" :style="{height:test?'150px':'0'}">
      <ElInput v-model="answer.stdin" v-if="inputing && test" class="textarea" type="textarea"></ElInput>
      <!-- {{msg}} -->
      <div class="out" v-if="!inputing && test" >
        {{ answer.msg }}
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import jsonWorker from 'monaco-editor/esm/vs/language/json/json.worker?worker'
import cssWorker from 'monaco-editor/esm/vs/language/css/css.worker?worker'
import htmlWorker from 'monaco-editor/esm/vs/language/html/html.worker?worker'
import tsWorker from 'monaco-editor/esm/vs/language/typescript/ts.worker?worker'
import EditorWorker from 'monaco-editor/esm/vs/editor/editor.worker?worker'
import * as monaco from 'monaco-editor';
import { nextTick, ref, onBeforeUnmount, toRefs, watch, onMounted, onUnmounted } from 'vue';
import {useRoute} from 'vue-router'
// import api from '../../api/api.js'
import { useClientStore } from '../pinia/stores/client';
import { gsap } from 'gsap'
import mitt from '@/mitt';

const client = useClientStore().client
const props = defineProps<{
  currentQuestion:{
    description:string,
    input:string,
    output:string,
    score:number
  } | undefined,
  answer:{
    text:string,
    stdin:string,
    language:string,
    msg:string
  },
  language:string,
  saveCode:Function
}>()
const { answer,language } = toRefs(props)
const lans = ['不限','cpp', 'rust', 'python3', 'go', 'javascript', 'java', 'C#','php',]
// const msg=ref('') 
// watch(() => answer.value.text,newValue =>{
//   if(!newValue){
//     editor.setValue('')
//   }
// },{deep:true}) 

const route=useRoute()
const loading=ref(false)

const inputing = ref(false)
const switchPanel = (input:boolean) => {
  if(!test.value){
    open()
  }
  inputing.value = input
}

const test = ref(false)
const height = ref(0)
const open = () =>{
  if(!test.value){
    gsap.to(height,{
      value:150
    })
    inputing.value = true
    // height.value = 150
  }
  else{
    gsap.to(height,{
      value:0
    })
    // height.value = 0
  }
  test.value = !test.value
}
// 
// MonacoEditor start
//
 onBeforeUnmount(()=>{
   editor.dispose() 
 })
// @ts-ignore
self.MonacoEnvironment = {
  getWorker(_: string, label: string) {
    if (label === 'json') {
      return new jsonWorker()
    }
    if (label === 'css' || label === 'scss' || label === 'less') {
      return new cssWorker()
    }
    if (label === 'html' || label === 'handlebars' || label === 'razor') {
      return new htmlWorker()
    }
    if (['typescript', 'javascript'].includes(label)) {
      return new tsWorker()
    }
    return new EditorWorker()
  },
}
let editor: monaco.editor.IStandaloneCodeEditor;

const editorInit = () => {
    nextTick(()=>{
        monaco.languages.typescript.javascriptDefaults.setDiagnosticsOptions({
            noSemanticValidation: true,
            noSyntaxValidation: false
        });
        monaco.languages.typescript.javascriptDefaults.setCompilerOptions({
            target: monaco.languages.typescript.ScriptTarget.ES2016,
            allowNonTsExtensions: true
        });
        
        !editor ? editor = monaco.editor.create(document.getElementById('codeEditBox') as HTMLElement, {
            value:answer.value.text, 
            language: answer.value.language, 
            automaticLayout: true, 
            foldingStrategy: 'indentation',
            renderLineHighlight: 'all', 
            selectOnLineNumbers: true, 
            minimap:{
                enabled: false,
            },
            readOnly: false,
            fontSize: 16,
            scrollBeyondLastLine: false, 
            overviewRulerBorder: false,
        }) : 
        editor.setValue("");
        // console.log(editor)
        editor.onDidChangeModelContent((val:any) => {
          console.log(answer.value);
          answer.value.text = editor.getValue();
             
        })
    })
}
editorInit()
// @ts-ignore
const changeLanguage=()=>{
  const model = editor.getModel()
  if(model) monaco.editor.setModelLanguage(model, answer.value.language)

  //  editor.updateOptions({
  //           language: "objective-c"
  //       });
}
const submitCode= async ()=>{
  props.saveCode()
  if(answer.value.language === '不限') return ElMessage.warning('请选择语言')
  loading.value=true
  // const ret = await request({
  //   url:'/code/run',
  //   method:'post',
  //   data:{
  //     code:answer.value.text,
  //     type:answer.value.language === 'javascript'?'nodejs':answer.value.language,
  //     stdin:answer.value.stdin
  //   }
  // })
  // console.log(ret);
  // if(ret.data.code === 0){
  //   if(ret.data.data.code === 0){
  //     answer.value.msg = ret.data.data.output
  //   }
  //   else if(ret.data.data.code === 2){
  //     ElMessage.warning('暂不支持该语言')
  //   }
  // }
  // else if(ret.data.code === 1){
  //   ElMessage.warning('暂不支持该语言')
  // }
  const ret = await client.callApi("RunCode/RunCode", {
      code:answer.value.text,
      type:(() =>{
        if(answer.value.language === 'javascript'){
          return 'nodejs'
        }
        if(answer.value.language === 'C#'){
          return 'dotnet'
        }
        return answer.value.language
      })(),
      stdin:answer.value.stdin
  });
  if(ret.isSucc){
    if(ret.res.ret.code === 0){
        ElMessage.success('运行成功')
        answer.value.msg = ret.res.ret.output
    }
    else if(ret.res.ret.code === 1){
        ElMessage.warning(ret.res.ret.message)
        answer.value.msg = ret.res.ret.output
    }
    else{
      ElMessage.warning('暂不支持该语言')
      answer.value.msg = ''
    }
  }

  loading.value = false
  inputing.value = false
  
  // api.submitCode(text.value,route.query.identity).then(res=>{
  //   loading.value=false
  //     if(res.data.code==200){
  //       msg.value=res.data.data.msg
      
  //       if(res.data.data.status==1){
  //           ElMessage.success(res.data.data.msg)
  //       }else{
  //            ElMessage.warning(res.data.data.msg)
  //       }
       

  //     }else{
  //       ElMessage.error(res.data.msg)
  //     }
  // })
}

onMounted(() =>{
  mitt.on('clear',(text)=>{
    console.log(text);
    editor.setValue(text as string)
  })
})

onUnmounted(()=>{
  mitt.off('clear')
})

</script>

<style scoped lang="less">
#codeEditBox {
  //  width: 100%;
  // height: 50%;
  height: calc(100% - 104px);
}
.select{
  padding: 10px 0;
}
.submit{
  text-align: left;
  padding: 10px 0;
  
}
.e-box{
  width: 100%;
  padding: 10px ;
  box-sizing: border-box;
  
  display: flex;
  // justify-content: space-between;
  box-sizing: border-box;
  flex-direction: column;
  text-align: left;
}
.sub-box{
  background-color: #fff;
  box-sizing: border-box;
  flex: 1;
  color: #696868;
  text-align: left;
  height: 36px;
  line-height: 36px;
  position: relative;
  z-index: 1;
  .select-plane{
    display: inline-block;
    // margin: 0 5px;
    cursor: pointer;
    padding: 0 10px;
    border-top-right-radius: 10px;
    border-top-left-radius: 10px;
    
    position: relative;
    
  }
  .on-panel{
    border: 1px solid #dcdfe6;
    &::after{
      content: ' ';
      position: absolute;
      height: 3px;
      width: 100%;
      left: 0;
      bottom: -2px;
      background: white;
    }
  }
  .btn{
    display: inline-block;
    height: 36px;
    line-height: 36px;
    float: right;
    cursor: pointer;
    width: 80px;
    text-align: center;
  }
}
.msg{
  background-color: #f6f6f6;
  border-bottom-left-radius: 5px;
  border-bottom-right-radius: 5px;
  position: relative;
  z-index: 0;
  //
  .out{
    padding:5px 11px;
    box-shadow: 0 0 0 1px #dcdfe6 inset;
    background-color: white;
    height: 100%;
    width: 100%;
    border-radius: 4px;
    overflow: auto;
    text-align: left;
    color: #606266;
    line-height: 1.5;
    font-weight: normal;
    font-size: 14px;
  }
}
</style>

<style lang="less">
.textarea{
  height: 100%;
  .el-textarea__inner{
    height: 100%!important;
    border: none!important;
  }
}
</style>